package middleware

import (
	"database/sql"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"ops.alert.center.service/internal/model"
	"strconv"
	"strings"
	"time"
)

var DB *gorm.DB

//参数含义:数据库用户名、密码、主机ip、连接的数据库、端口号
func DBConn(User, Password, Host, Db string, Port int) *gorm.DB {
	connArgs := fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", User, Password, Host, Port, Db)
	db, err := gorm.Open("mysql", connArgs)
	if err != nil {
		return nil
	}
	db.SingularTable(true) //如果使用gorm来帮忙创建表时，这里填写false的话gorm会给表添加s后缀，填写true则不会
	db.LogMode(true)       //打印sql语句
	//开启连接池
	db.DB().SetMaxIdleConns(100)   //最大空闲连接
	db.DB().SetMaxOpenConns(10000) //最大连接数
	db.DB().SetConnMaxLifetime(30) //最大生存时间(s)
	InitDB(User, Password, Host, Db)
	return db
}

var DBSQl *sql.DB

func InitDB(User, Password, Host, Db string) error {
	fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "数据库连接成功")
	path := strings.Join([]string{User, ":", Password, "@tcp(", Host, ":", "3306", ")/", Db, "?charset=utf8"}, "")
	DBSQl, _ = sql.Open("mysql", path)
	DBSQl.SetConnMaxLifetime(1000)
	DBSQl.SetMaxIdleConns(1000)
	if err := DBSQl.Ping(); err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "数据库连接失败")
		return err
	}
	return nil
}

var ThisAlertsubscriptions []model.Alertsubscription
var ThisAlertcontact []model.Alertcontact
var ThisZhaoapplication []model.Zhaoapplication
var ThisAlertways []model.Alertways

func GetDb() (conn *gorm.DB) {
	for {
		this_port, _ := strconv.Atoi(Port)
		conn = DBConn(UserName, Password, Ip, DbName, this_port)
		if conn != nil {
			break
		}
		fmt.Println("本次未获取到mysql连接")
	}
	DB = conn
	return conn
}

//获取告警中心订阅应用的数据
func GetAlertsubscriptionAllData() {
	result := DB.Find(&ThisAlertsubscriptions)
	fmt.Println("总共笔数", result.RowsAffected)
}

//获取告警中心订阅应用的数据
func GetalertcontactAllData() {
	result := DB.Find(&ThisAlertcontact)
	fmt.Println("总共笔数", result.RowsAffected)
}

//获取告警中心所有的应用名称
func GetZhaoapplicatinAllData() {
	result := DB.Find(&ThisZhaoapplication)
	fmt.Println("总共笔数", result.RowsAffected)
}
func GetAppNameByAppID(appId int) (appName string) {
	for _, zhaoapplication := range ThisZhaoapplication {
		if zhaoapplication.App_id == appId {
			return zhaoapplication.Name
		}
	}
	return
}

//获取告警中心所有的方式
func GetAlertwaysAllData() {
	result := DB.Find(&ThisAlertways)
	fmt.Println("总共笔数", result.RowsAffected)
}
